package com.demo.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.modules.sys.dao.SysUserRoleDao;
import com.demo.modules.sys.entity.SysRoleEntity;
import com.demo.modules.sys.entity.SysUserRoleEntity;
import com.demo.modules.sys.service.SysUserRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;



/**
 * 用户与角色对应关系
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserRoleService")
@AllArgsConstructor
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {


	@Override
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
		//先删除用户与角色关系
		this.remove(new LambdaQueryWrapper<SysUserRoleEntity>().eq(SysUserRoleEntity::getUserId, userId));

		if(roleIdList == null || roleIdList.size() == 0){
			return ;
		}

		//保存用户与角色关系
		for(Long roleId : roleIdList){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);

			this.save(sysUserRoleEntity);

			//同步流程引擎用户与用户组关系绑定
			//identityService.deleteMembership(String.valueOf(userId),String.valueOf(roleId));
			//identityService.createMembership(String.valueOf(userId),String.valueOf(roleId));
		}
	}

	@Override
	public void saveOrUpdateRole(Long roleId, List<Long> userIdList) {
		//先删除用户与角色关系
		this.remove(new LambdaQueryWrapper<SysUserRoleEntity>().eq(SysUserRoleEntity::getRoleId, roleId));

		if(userIdList == null || userIdList.size() == 0){
			return ;
		}

		//保存用户与角色关系
		for(Long userId : userIdList){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);

			this.save(sysUserRoleEntity);

			//同步流程引擎用户与用户组关系绑定
			//identityService.deleteMembership(String.valueOf(userId),String.valueOf(roleId));
			//identityService.createMembership(String.valueOf(userId),String.valueOf(roleId));
		}
	}

	@Override
	public List<SysRoleEntity> queryRoleList(Long userId) {
		return baseMapper.queryRoleList(userId);
	}

	@Override
	public List<Long> queryRoleIdList(Long userId) {
		return baseMapper.queryRoleIdList(userId);
	}

	@Override
	public List<Long> queryUserIdList(Long roleId) {
		return baseMapper.queryUserIdList(roleId);
	}

	@Override
	public int deleteBatch(Long[] roleIds){
		return baseMapper.deleteBatch(roleIds);
	}
}
